#include "main_interface.h"
#include "ui_main_interface.h"

#include <QToolTip>
#include <QDebug>
#include <QMessageBox>
#include <QTimer>
#include <QSqlError>

MainInterface::MainInterface(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainInterface)
{
    ui->setupUi(this);

    initializeSetStyleSheet();

    initializeTableHash();

    initializeTableViewModel();

    initializeInformationManagePage();

    //搜索按钮
    connect(ui->searchPushButton, &QPushButton::clicked, this, &MainInterface::searchTableData);

    //改变选表产生的事件
    connect(ui->tableSelectComboBox, static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentIndexChanged),
            this, [&](QString selectItemText){
        //修改的主键清空
        m_primaryKeyValuePreviousHash.clear();
        //修改位置清空
        m_alterPosition.clear();
        //现在的页码
        m_nowPage = 1;

        //下拉选项框的字段显示
        tableFieldComboxShow(m_use2TableNameHash[selectItemText]);
        //表的数据
        allTableInformationShow();

    });

    //批量修改按钮
    connect(ui->batchAlterPushButton, &QPushButton::clicked, this, &MainInterface::batchAlterRecord);

    //批量删除
    connect(ui->batchDeletePushButton, &QPushButton::clicked, this, &MainInterface::batchDeleteRecord);

    //跳转页
    connect(ui->jumpPagePushButton, &QAbstractButton::clicked,
            this, [&](){
                if(m_recordAmount > 0){
                    int nowPage = ui->pageLineEdit->text().toInt();
                    qDebug()<<"nowPage:"<<nowPage;

                    if(nowPage > m_pageAmount){//输入的页数大于最大页
                        m_nowPage = 1;
                        ui->pageLineEdit->setText(QString::number(m_nowPage));
                    }else{
                        m_nowPage = nowPage;
                    }

                    if(m_lineEditText.size() == 0){
                        allTableInformationShow();
                    }else{
                        partTableInformationShow();
                    }
                }
            });

    //第一页
    connect(ui->firstPagePushButton, &QAbstractButton::clicked,
            this, [&](){
                if(m_recordAmount > 0){
                    m_nowPage = 1;
                    ui->pageLineEdit->setText(QString::number(m_nowPage));
                    if(m_lineEditText.size() == 0){
                        allTableInformationShow();
                    }else{
                        partTableInformationShow();
                    }
                }
            });

    //最后一页
    connect(ui->lastPagePushButton, &QAbstractButton::clicked,
            this, [&](){
                if(m_recordAmount > 0){
                    m_nowPage = m_pageAmount;
                    ui->pageLineEdit->setText(QString::number(m_nowPage));
                    if(m_lineEditText.size() == 0){
                        allTableInformationShow();
                    }else{
                        partTableInformationShow();
                    }
                }
            });

    //上一页
    connect(ui->previousPagePushButton, &QAbstractButton::clicked,
            this, [&](){
                if(m_recordAmount > 0){
                    m_nowPage = ((m_nowPage == 1)?1:(m_nowPage-1));
                    ui->pageLineEdit->setText(QString::number(m_nowPage));
                    if(m_lineEditText.size() == 0){
                        allTableInformationShow();
                    }else{
                        partTableInformationShow();
                    }
                }
            });

    //下一页
    connect(ui->nextPagePushButton, &QAbstractButton::clicked,
            this, [&](){
                if(m_recordAmount > 0){
                    m_nowPage = ((m_nowPage == m_pageAmount)?m_pageAmount:(m_nowPage+1));
                    ui->pageLineEdit->setText(QString::number(m_nowPage));
                    if(m_lineEditText.size() == 0){
                        allTableInformationShow();
                    }else{
                        partTableInformationShow();
                    }
                }
            });

}

MainInterface::~MainInterface()
{
    delete ui;
}

void MainInterface::initializeSetStyleSheet()
{
    //第一页
    ui->firstPagePushButton->setStyleSheet("QPushButton{border-image: url(:/Image/firstPage.png)}");
    //前一页
    ui->previousPagePushButton->setStyleSheet("QPushButton{border-image: url(:/Image/previousPage.png)}");
        //下一页
    ui->nextPagePushButton->setStyleSheet("QPushButton{border-image:url(:/Image/nextPage.png)}");
    //最后一页
    ui->lastPagePushButton->setStyleSheet("QPushButton{border-image:url(:/Image/lastPage.png)}");
    //跳转页
    ui->jumpPagePushButton->setStyleSheet("QPushButton{border-image:url(:/Image/jumpPage.png)}");
    //页数输入
    ui->pageLineEdit->setStyleSheet("background-color:white;border-width:0;border-style:outset;color:black;solid white");
    //批量保存
    // ui->batchAlterPushButton->setIcon(QIcon(":/Image/batchSave.png"));
    // ui->batchAlterPushButton->setIconSize(QSize(ui->batchAlterPushButton->width(), ui->batchAlterPushButton->height()));
    // ui->batchAlterPushButton->setStyleSheet("QPushButton{background:rgba(0,0,0,0);border:1px solid rgba(0,0,0,0);}");


    //输入框样式
    ui->searchLineEdit->setPlaceholderText(QStringLiteral("请输入要查询的内容"));
}

void MainInterface::initializeTableHash()
{
    m_tableName2UseHash["student_information"] = "学生信息表";

    QPair<QString, QString> pair;
    m_tableFieldName2UseHash[QPair("student_information", "student_id")] = "编号";
    m_tableFieldName2UseHash[QPair("student_information","name")] = "姓名";
    m_tableFieldName2UseHash[QPair("student_information","sex")] = "性别";
    m_tableFieldName2UseHash[QPair("student_information","categorization")] = "工种";
    m_tableFieldName2UseHash[QPair("student_information","section")] = "部门";
    m_tableFieldName2UseHash[QPair("student_information","class")] = "班级";
    m_tableFieldName2UseHash[QPair("student_information","job_category")] = "分类";
    m_tableFieldName2UseHash[QPair("student_information","title")] = "职称";
    m_tableFieldName2UseHash[QPair("student_information","work_unit")] = "单位";
    m_tableFieldName2UseHash[QPair("student_information","remark")] = "备注";

    m_use2TableNameHash["学生信息表"] = "student_information";

    m_use2TableFieldNameHash[QPair("学生信息表", "编号")] = "student_id";
    m_use2TableFieldNameHash[QPair("学生信息表","姓名")] = "name";
    m_use2TableFieldNameHash[QPair("学生信息表","性别")] = "sex";
    m_use2TableFieldNameHash[QPair("学生信息表","工种")] = "categorization";
    m_use2TableFieldNameHash[QPair("学生信息表","部门")] = "section";
    m_use2TableFieldNameHash[QPair("学生信息表","班级")] = "class";
    m_use2TableFieldNameHash[QPair("学生信息表","分类")] = "job_category";
    m_use2TableFieldNameHash[QPair("学生信息表","职称")] = "title";
    m_use2TableFieldNameHash[QPair("学生信息表","单位")] = "work_unit";
    m_use2TableFieldNameHash[QPair("学生信息表","备注")] = "remark";

    m_tableName2UseHash["teacher_information"] = "教师信息表";

    m_tableFieldName2UseHash[QPair("teacher_information", "teacher_id")] = "编号";
    m_tableFieldName2UseHash[QPair("teacher_information","name")] = "姓名";
    m_tableFieldName2UseHash[QPair("teacher_information","role")] = "角色";

    m_use2TableNameHash["教师信息表"] = "teacher_information";
    m_use2TableFieldNameHash[QPair("教师信息表", "编号")] = "teacher_id";
    m_use2TableFieldNameHash[QPair("教师信息表","姓名")] = "name";
    m_use2TableFieldNameHash[QPair("教师信息表","角色")] = "role";


    m_tableName2UseHash["permission_manage_information"] = "角色信息表";

    m_tableFieldName2UseHash[QPair("permission_manage_information", "user_id")] = "用户编号";
    m_tableFieldName2UseHash[QPair("permission_manage_information", "role_id")] = "角色";

     m_use2TableNameHash["角色信息表"] = "permission_manage_information";

    m_use2TableFieldNameHash[QPair("角色信息表", "用户编号")] = "user_id";
    m_use2TableFieldNameHash[QPair("角色信息表", "角色")] = "role_id";

}

void MainInterface::initializeTableViewModel()
{
    //显示鼠标显示tableView上的文字信息
    //开启界面鼠标捕获功能
    ui->recordsTableView->viewport()->setMouseTracking(true);

    //显示鼠标显示tableView上的文字信息
    //开启界面鼠标捕获功能
    ui->recordsTableView->viewport()->setMouseTracking(true);
    connect(ui->recordsTableView, &QTableView::entered,
            this, [](const QModelIndex &index)
            {
                if(index.isValid() == false) return;
                else{
                    // qDebug()<<"index.data().toString():"<<index.data().toString();
                    QToolTip::showText(QCursor::pos(), index.data().toString());
                }
            }
            );

    //1 数据模型
    m_tableDataModel = new QStandardItemModel(this);
    //2 选择模型
    m_selectionModel = new QItemSelectionModel(m_tableDataModel);
    //3 设置模型
    ui->recordsTableView->setModel(m_tableDataModel);
    ui->recordsTableView->setSelectionModel(m_selectionModel);

    //选择行为
    ui->recordsTableView->setSelectionBehavior (QAbstractItemView::SelectRows);
    //ui->recordsTableView->setSelectionMode ( QAbstractItemView::SingleSelection);
    ui->recordsTableView->setAlternatingRowColors(true);

    //隐藏左边的列名
    ui->recordsTableView->verticalHeader()->hide();

    //根据内容自适应宽度
    ui->recordsTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->recordsTableView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);

    //设置最大和最小列宽
    ui->recordsTableView->horizontalHeader()->setMinimumSectionSize(104);
    ui->recordsTableView->horizontalHeader()->setMaximumSectionSize(200);

    connect(ui->recordsTableView->itemDelegate(),&QAbstractItemDelegate::closeEditor,this,[&](){
        //记录被修改的行,方便批量修改
        m_alterRows.insert(m_selectionModel->currentIndex().row());
        //记录被修改的位置
        m_alterPosition[m_selectionModel->currentIndex().row()].append(m_selectionModel->currentIndex().column());
    });

   // connect(ui->recordsTableView, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(ClickCell(const QModelIndex &)));

    //记录编辑之前的主键值
    connect(ui->recordsTableView, &QTableView::doubleClicked, this, [&](const QModelIndex& modelIndex){
        QModelIndex tmpIndex =  m_tableDataModel->index(modelIndex.row(), m_primaryKeyColumnIndex);
        QVariant keyValue = m_tableDataModel->data(tmpIndex);

        qDebug()<<"编辑过行："<<modelIndex.row();
        qDebug()<<"编辑过行的主键"<<m_tableDataModel->data(tmpIndex);

        //主键没有在其中，就添加
        if(m_primaryKeyValuePreviousHash.find(keyValue.toInt()) != m_primaryKeyValuePreviousHash.end()){

        }else{
            qDebug()<<"添加编辑行的主键数据";
            m_primaryKeyValuePreviousHash[modelIndex.row()] = m_tableDataModel->data(tmpIndex);
        }

        //打印映射表
        QHash<int, QVariant>::const_iterator iter = m_primaryKeyValuePreviousHash.constBegin();
        while(iter != m_primaryKeyValuePreviousHash.constEnd()){
            qDebug()<<"iter.key()"<<iter.key();
            qDebug()<<"iter.value()"<<iter.value();
            iter++;
        }

    });

    // connect(m_tableDataModel, &QStandardItemModel::itemChanged, this, [&](QStandardItem *item){
    //     qDebug()<<item->data();
    // });

    //阻塞信号
    ui->recordsTableView->itemDelegate()->blockSignals(true);
}

void MainInterface::initializeInformationManagePage()
{
    //添加表信息
    QSqlQuery query(QSqlDatabase::database("mysql_connection1"));

    QString tmpSql = QString("SHOW TABLES");
    query.exec(tmpSql);
    int index = 0;
    while(query.next()){
        QString tableName = query.value(0).toString();

        //如果表没有在映射表中，就不显示
        if(m_tableName2UseHash.find(tableName) != m_tableName2UseHash.end()){
            ui->tableSelectComboBox->addItem(m_tableName2UseHash[tableName]);

            if(index == 0){
                ui->tableSelectComboBox->setCurrentText(m_tableName2UseHash[tableName]);
                tableFieldComboxShow(tableName);
            }
            index++;
        }
    }
}

void MainInterface::tableInformationTableViewDataShowBySqlQuery(QSqlQuery &query)
{
    // //设置行和列
    int row = 0;
    while(query.next()){
        row++;
    }
    query.seek(-1);

    m_tableDataModel->setRowCount(row);

    row = 0;
    //设置表中值
    while(query.next()){
        for(int colNum = 0;colNum < m_tableFieldQueue.size();colNum++){
            QModelIndex index =  m_tableDataModel->index(row, colNum);
            m_tableDataModel->setData(index, query.value(colNum), Qt::DisplayRole);

            // m_tableDataModel->setItem(row, colNum, new QStandardItem(query.value(colNum).toString()));
        }
        row++;
    }

    ui->recordsTableView->setModel(m_tableDataModel);
    ui->recordsTableView->show();

    //默认选中第一行
    QItemSelection selection(m_tableDataModel->index(0, 0), m_tableDataModel->index(0, m_tableDataModel->columnCount() - 1));
    m_selectionModel->select(selection,  QItemSelectionModel::Select);

    //记录被修改过的行
    m_alterRows.clear();
    ui->recordsTableView->itemDelegate()->blockSignals(false);

}

void MainInterface::allTableInformationShow()
{
    QSqlQuery query(QSqlDatabase::database("mysql_connection1"));

    //表头栏显示
    tableViewHeadingShow();

    QString tmpSql = QString("SELECT ");
    int row = 0;
    //拼接查询字段名
    foreach (QString tableField, m_tableFieldQueue){
        if(row > 0){
            tmpSql += ",";
        }
        row++;
        tmpSql += tableField;
    }
    tmpSql += QString(" FROM ");
    tmpSql += m_use2TableNameHash[ui->tableSelectComboBox->currentText()];
    qDebug()<<"tmpSql:"<<tmpSql;
    query.exec(tmpSql);
    //统计总页数
    m_recordAmount = 0;
    while(query.next()) m_recordAmount++;
    m_pageAmount = (m_recordAmount%m_pageUnit == 0)?(m_recordAmount/m_pageUnit):(m_recordAmount/m_pageUnit+1);

    ui->totalPageLabel->setText("共" + QString::number(m_pageAmount) + "页");
    ui->pageInformationLabel->setText("显示" + QString::number((m_nowPage - 1)*m_pageUnit + 1) + "到" + QString::number((m_nowPage*m_pageUnit>m_recordAmount)?m_recordAmount:(m_nowPage*m_pageUnit))+"，共"+ QString::number(m_recordAmount) + "条记录");
    ui->pageLineEdit->setText(QString::number(m_nowPage));


    tmpSql += QString(" LIMIT %1 OFFSET %2").arg(m_pageUnit).arg((m_nowPage - 1)*m_pageUnit);
    // tmpSql = QString("SELECT student_id,name,sex,section,job_category,categorization,class,title,work_unit,remark FROM student_information LIMIT %1 OFFSET %2").arg(m_pageUnit).arg((m_nowPage - 1)*m_pageUnit);
    query.exec(tmpSql);

    tableInformationTableViewDataShowBySqlQuery(query);

}

void MainInterface::partTableInformationShow(){
    m_lineEditText = ui->searchLineEdit->text();

    QSqlQuery query(QSqlDatabase::database("mysql_connection1"));

    //表头栏显示，并返回字段名
    tableViewHeadingShow();

    QString tmpSql = QString("SELECT ");
    int row = 0;
    //拼接查询字段名
    foreach (QString tableField, m_tableFieldQueue){
        if(row > 0){
            tmpSql += ",";
        }
        row++;
        tmpSql += tableField;
    }
    tmpSql += QString(" FROM ");
    tmpSql += m_use2TableNameHash[ui->tableSelectComboBox->currentText()];
    tmpSql += QString(" WHERE ") + m_use2TableFieldNameHash[QPair(ui->tableSelectComboBox->currentText(), ui->tableFieldSelectComboBox->currentText())];
    tmpSql += QString(" LIKE \'%%1%\'").arg(m_lineEditText);
   // qDebug()<<"tmpSql:"<<tmpSql;
    query.exec(tmpSql);

    //统计总页数
    m_recordAmount = 0;
    while(query.next()) m_recordAmount++;
    m_pageAmount = (m_recordAmount%m_pageUnit == 0)?(m_recordAmount/m_pageUnit):(m_recordAmount/m_pageUnit+1);

    ui->totalPageLabel->setText("共" + QString::number(m_pageAmount) + "页");
    ui->pageInformationLabel->setText("显示" + QString::number((m_nowPage - 1)*m_pageUnit + 1) + "到" + QString::number((m_nowPage*m_pageUnit>m_recordAmount)?m_recordAmount:(m_nowPage*m_pageUnit))+"，共"+ QString::number(m_recordAmount) + "条记录");
    ui->pageLineEdit->setText(QString::number(m_nowPage));

    tmpSql += QString(" LIMIT %1 OFFSET %2").arg(m_pageUnit).arg((m_nowPage - 1)*m_pageUnit);
    // tmpSql = QString("SELECT student_id,name,sex,section,job_category,categorization,class,title,work_unit,remark FROM student_information LIMIT %1 OFFSET %2").arg(m_pageUnit).arg((m_nowPage - 1)*m_pageUnit);
    query.exec(tmpSql);
    tableInformationTableViewDataShowBySqlQuery(query);

}

void MainInterface::tableViewHeadingShow()
{
    m_tableDataModel->clear();
    //添加表字段信息
    m_tableFieldQueue.clear();//保存表的字段名（控制select中字段值顺序）

    //移除之前的数据
    m_tableDataModel->removeRows(0, m_tableDataModel->rowCount());
    //水平表头可见
    ui->recordsTableView->horizontalHeader()->setVisible(true);

    QSqlQuery query(QSqlDatabase::database("mysql_connection1"));

    QString  tmpSql = QString("DESCRIBE ") + m_use2TableNameHash[ui->tableSelectComboBox->currentText()];
    query.exec(tmpSql);
    int row = 0;
    while(query.next()){
        //m_tableDataModel->setHorizontalHeaderItem(row, new QStandardItem(m_tableFieldName2UseHash[QPair(m_use2TableNameHash[ui->tableSelectComboBox->currentText()], query.value(0).toString())]));
        // qDebug()<<"m_use2TableNameHash[ui->tableSelectComboBox->currentText()]:"<<m_use2TableNameHash[ui->tableSelectComboBox->currentText()];
        // qDebug()<<"query.value(0).toString():"<<query.value(0).toString();
        // m_tableDataModel->setHorizontalHeaderItem(0, new QStandardItem("编号"));
        //setItem没有则会新增，setData仅修改已存在的项
        //设置表头，如不设置则使用数据库中的默认表头
        QString filedName = query.value(0).toString();
        m_tableFieldQueue.enqueue(filedName);
        m_tableDataModel->setHorizontalHeaderItem(row, new QStandardItem(m_tableFieldName2UseHash[QPair(m_use2TableNameHash[ui->tableSelectComboBox->currentText()], filedName)]));
        row++;
    }
}

void MainInterface::batchAlterRecord()
{
    if(m_alterRows.size() == 0){
        QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("没有修改过的数据！"));
        QTimer::singleShot(1500, infoBox,&QMessageBox::deleteLater);
        infoBox->show();
        return;
    }

    auto button = QMessageBox::question(this,  tr("信息提示"),
                                        QString("是否确认对修改过的%1行数据进行修改？").arg(m_alterRows.size()),  QString("确定"), QString("取消"), 0);

    if (button == 0) {//修改记录信息

        QSqlDatabase::database().transaction();//开始事务
        QSqlQuery query(QSqlDatabase::database("mysql_connection1"));

        //UPDATE table_anem SET column_name1 = value1, column_name2 = value2... WHERE
        QString tmpSql = QString("UPDATE ");
        tmpSql += m_use2TableNameHash[ui->tableSelectComboBox->currentText()];
        tmpSql += QString(" SET ");

        QHash<QString, QVariantList> tableAlterFiledValue;
        QHash<QString, QVariantList> tableAlterPrimaryKeyValue;
        int row = 0;
        foreach (QString tableField, m_tableFieldQueue){
            if(row > 0){
                tmpSql += ",";
            }
            row++;
            tmpSql += tableField + QString(" = ?");
        }

        tmpSql += QString(" WHERE ") + m_tablePrimaryKeyField.toString()  + QString(" = ?");
        query.prepare(tmpSql);
        //qDebug()<<tmpSql;

        foreach(int rowNum, m_alterRows){
            qDebug()<<"rowNum:"<<rowNum;
            //QVariantList

            int colNum = 0;
            //获得每个变量改变的值
            foreach (QString tableField, m_tableFieldQueue) {
                //判断更新的主键和之前的主键有没有重复(有重复则不更新)
                if(colNum == m_primaryKeyColumnIndex){
                    if(m_tableDataModel->data(m_tableDataModel->index(rowNum, colNum)) != m_primaryKeyValuePreviousHash[rowNum]){
                        if(judgePrimaryKeyIsExistence(m_tableDataModel->data(m_tableDataModel->index(rowNum, colNum)).toString())){
                            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("修改的数据有重复的数据，请重新修改！"));
                            QTimer::singleShot(1500, infoBox,&QMessageBox::deleteLater);
                            infoBox->show();
                            //清空修改后的数据
                            searchTableData();
                            return;
                        }
                    }
                }
                tableAlterFiledValue[tableField].append(m_tableDataModel->data(m_tableDataModel->index(rowNum, colNum)));
                colNum++;
            }
            qDebug()<<"m_primaryKeyValuePreviousHash[row]:"<<m_primaryKeyValuePreviousHash[rowNum];
            tableAlterPrimaryKeyValue[m_tablePrimaryKeyField.toString()].append(m_primaryKeyValuePreviousHash[rowNum]);
        }

        //绑定变量值set value
        foreach (QString tableField, m_tableFieldQueue) {
            query.addBindValue(tableAlterFiledValue[tableField]);
        }

        query.addBindValue(tableAlterPrimaryKeyValue[m_tablePrimaryKeyField.toString()]);

        if(!query.execBatch()){
            qDebug()<<query.lastError().text();
        }

        QSqlDatabase::database().commit();//提交事务

        //修改后的数据清空
        m_alterRows.clear();
        m_alterPosition.clear();
        m_primaryKeyValuePreviousHash.clear();

        searchTableData();

    }
}

void MainInterface::batchDeleteRecord()
{
    //先判断是否有数据已经修改，若已经修改，则需要先保存修改，再删除
    if(m_primaryKeyValuePreviousHash.size() > 0){
        QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("请先保存修改后的数据，再删除，谢谢！"));
        QTimer::singleShot(2000, infoBox,&QMessageBox::deleteLater);
        infoBox->show();
        return;
    }

    //获取选择模型的指针
    QItemSelectionModel *selections =  ui->recordsTableView->selectionModel();
    //获取被选中的指针列表
    QModelIndexList selected = selections->selectedIndexes();
    //初始化删除行和删除的id
    m_deleteRows.clear();

    foreach (QModelIndex index, selected) {
        m_deleteRows.insert(index.row());
    }

    if(m_deleteRows.size() == 0){//没有被选中的行
        QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("没有选择删除的行！"));
        QTimer::singleShot(1500, infoBox,&QMessageBox::deleteLater);
        infoBox->show();
        return;
    }

    auto button = QMessageBox::question(this,  tr("信息提示"),
                                        QString("是否确认要删除这%1行数据？").arg(m_deleteRows.size()),  QString("确定"), QString("取消"), 0);
    if (button == 0) {//删除记录信息
        QSqlQuery query(QSqlDatabase::database("mysql_connection1"));
        //delete from student_information WHERE student_id in(3,5,6,8);
        QString tmpSql = QString("DELETE FROM ");
        tmpSql += m_use2TableNameHash[ui->tableSelectComboBox->currentText()];
        tmpSql += QString(" WHERE ") + m_tablePrimaryKeyField.toString() + QString(" in(");

        int index = 0;
        foreach(int rowNum, m_deleteRows){
            if(index > 0){
                tmpSql += ",";
            }
            index++;
            tmpSql += m_tableDataModel->data(m_tableDataModel->index(rowNum, 0)).toString();
        }

        tmpSql += QString(")");
        //qDebug()<<tmpSql;

        if(!query.exec(tmpSql)){
            qDebug()<<query.lastError().text();
        }
    }
    searchTableData();
}

void MainInterface::tableFieldComboxShow(QString tableName)
{
    ui->tableFieldSelectComboBox->clear();

    QSqlQuery query2(QSqlDatabase::database("mysql_connection1"));
    //添加表字段信息
    QString tmpSql = QString("DESCRIBE ") + tableName;
    qDebug()<<tmpSql;
    query2.exec(tmpSql);
    int primarkKeyColumnIndex = 0;//主键的列号
    while(query2.next()){
        QString fieldName = query2.value(0).toString();
        qDebug()<<fieldName;
        ui->tableFieldSelectComboBox->addItem(m_tableFieldName2UseHash[QPair(m_use2TableNameHash[ui->tableSelectComboBox->currentText()] , fieldName)]);
        if(query2.value(3).toString() == "PRI"){
            m_tablePrimaryKeyField = fieldName;
            m_primaryKeyColumnIndex = primarkKeyColumnIndex;
            //qDebug()<<"m_tablePrimaryKey:"<<m_tablePrimaryKey;
        }
        primarkKeyColumnIndex++;
    }
}

bool MainInterface::judgePrimaryKeyIsExistence(QString primaryKeyField)
{
    QSqlQuery query(QSqlDatabase::database("mysql_connection1"));
    QString tmpSql = "SELECT ";
    tmpSql += primaryKeyField;
    tmpSql += QString(" FROM ") + m_use2TableNameHash[ui->tableSelectComboBox->currentText()];
    if(!query.exec(tmpSql)){
        qDebug()<<query.lastError().databaseText();
    }else{
        while(query.next()){
            return true;
        }
         return false;
    }
    return true;
}

void MainInterface::searchTableData()
{
    m_nowPage = 1;
    if(ui->searchLineEdit->text().size() == 0){
        allTableInformationShow();
    }else{

        partTableInformationShow();
    }
}

